﻿Number.prototype.formatBytes = function() {
    var units = ['B', 'KB', 'MB', 'GB', 'TB'],
        bytes = this,
        i;
 
    for (i = 0; bytes >= 1024 && i < 4; i++) {
        bytes /= 1024;
    }
 
    return bytes.toFixed(2) + units[i];
}




function ChunkedUploader(file, options) {
    if (!this instanceof ChunkedUploader) {
        return new ChunkedUploader(file, options);
    }

    var self = this;
    this.file = file;
    console.log(self);
    self.uploadFileName = self.file.name + Math.floor(Math.random() * 10000000)
    this._upload= function() {
        //var self = this,
          var  chunk;
 
        // Slight timeout needed here (File read / AJAX readystate conflict?)
        setTimeout(function() {
            // Prevent range overflow
            if (self.range_end > self.file_size) {
                self.range_end = self.file_size;
            }
 
            chunk = self.file[self.slice_method](self.range_start, self.range_end);
 
            self.upload_request.open('PUT', self.options.url, true);
            self.upload_request.overrideMimeType('application/octet-stream');
            self.upload_request.setRequestHeader('ufilename', self.uploadFileName);
            console.log(self.file);
            if (self.range_start !== 0) {
                self.upload_request.setRequestHeader('Content-Range', 'bytes ' + self.range_start + '-' + self.range_end + '/' + self.file_size);
            }
 
            self.upload_request.send(chunk);
 
            
        }, 20);
    }

    this._onChunkComplete=function() {
        // If the end range is already the same size as our file, we
        // can assume that our last chunk has been processed and exit
        // out of the function.
        if (self.range_end === self.file_size) {
            self._onUploadComplete();
            return;
        }
 
        // Update our ranges
        self.range_start = self.range_end;
        self.range_end = self.range_start + self.chunk_size;
        self.statusLi.html("uploading "+self.range_start + " of " + self.file_size)
        // Continue as long as we aren't paused
        if (!self.is_paused) {
            self._upload();
        }
    }

    this._onUploadComplete=function()
    {
        //alert('upload complete');
        self.statusLi.html("Converting...")
        console.log('complete');
        self.SaveToStorage();
    }

    this.SaveToStorage = function ()
    {
        console.log('checking status');
        var url = self.options.url + "?op=complete&file=" + encodeURIComponent(self.uploadFileName)
            + "&exp=" + encodeURIComponent($('#selExpiration').val())
            + "&forcedownload=" + encodeURIComponent($('#checkBoxForceDownload').prop('checked'))
            + "&filename=" + encodeURIComponent(self.file.name)
            + "&remlink=" + encodeURIComponent($('#checkBoxGenerateRemoveLink').prop('checked'));
        $.get({
            cache: false,
            url: url,
            error:function(err)
            {
                console.log(err);
            },
            success:function (data)
            {
                
                console.log(data);
                
                if (data.status == 'Uploaded')
                {
                    var statusHtml = data.url;
                    self.statusLi.html(statusHtml)
                }
                else if (data.status == 'Error')
                {
                    self.statusLi.html("Error")
                }
                else
                {
                    console.log('setting timeout');
                    window.setTimeout(function () { self.SaveToStorage() }, 2000);
                }
            }
           
        });

    }

    this.start=function() {
        self._upload();
    }

    
    this.pause= function() {
        self.is_paused = true;
    }

    this.resume= function() {
        self.is_paused = false;
        self._upload();
    }

    this.options = $.extend({
        url: '/u.axd'
    }, options);
 



    this.file_size = this.file.size;
    this.chunk_size = (1024 * 500); // 500KB
    this.range_start = 0;
    this.range_end = this.chunk_size;
 
    if ('mozSlice' in this.file) {
        this.slice_method = 'mozSlice';
    }
    else if ('webkitSlice' in this.file) {
        this.slice_method = 'webkitSlice';
    }
    else {
        this.slice_method = 'slice';
    }
 
    this.upload_request = new XMLHttpRequest();
    this.upload_request.onload = this._onChunkComplete;

    
    
}
 



$(document).ready(function () {

    return;
    onFileSelected = function(e) {
        var files = e.target.files;

        for (var i = 0; i < files.length; i++) {
            file_list.append('<li>' + files[i].name + '(' + files[i].size.formatBytes() + ')</li>');
        }

        file_list.show();
        submit_btn.attr('disabled', false);
    }

    var file_input = $('#file_input'),
        file_list = $('#file_list'),
        submit_btn = $('#submit_btn');
    console.log(file_input);
    file_input.on('change', onFileSelected);
 
    /**
     * Loops through the selected files, displays their file name and size
     * in the file list, and enables the submit button for uploading.
     */
    
});

var uploaders = [];
$(document).ready(function() {
    var upload_form = $('#upload_form'),
        file_input = $('#file_input'),
        file_list = $('#file_list'),
        submit_btn = $('#submit_btn');
       
 
    file_input.on('change', onFilesSelected);
    //upload_form.on('submit', onFormSubmit);
 
    /**
     * Loops through the selected files, displays their file name and size
     * in the file list, and enables the submit button for uploading.
     */
    function onFilesSelected(e) {
        var files = e.target.files,
            file;
 
        for (var i = 0; i < files.length; i++) {
            file = files[i];
            var uploader = new ChunkedUploader(file);
            uploaders.push(uploader);
            var statusLi = $('<li>' + file.name + '(' + file.size.formatBytes() + ')</li>')
            uploader.statusLi = statusLi
            file_list.append(statusLi);
        }
 
        file_list.show();
        submit_btn.attr('disabled', false);
    }
 
    /**
     * Loops through all known uploads and starts each upload
     * process, preventing default form submission.
     */
    
});

function onStartUpload(e) {
    $.each(uploaders, function (i, uploader) {
        uploader.start();
    });
    $('#submit_btn').attr('disabled', 'disabled');;
    $('#uploadPane').hide();
    $('#optionsPane').hide();
    $('#selectedFileHeading').html("Copy the urls once the upload is completed !")
    // Prevent default form submission
   // e.preventDefault();
}